package com.whksoft.mymapplugin.Listener;

import com.whksoft.mymapplugin.API.Event.PaymentCanceledEvent;
import com.whksoft.mymapplugin.utils.CancelReason;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.Plugin;

import static com.whksoft.mymapplugin.utils.flagUtils.haveQRFlag;

/**
 * 检测玩家右键
 */
public class rightClick implements Listener {

    Plugin plugin;

    public rightClick(Plugin plugin) {
        this.plugin = plugin;
    }

    //玩家右键快捷栏工具事件
    @EventHandler(priority = EventPriority.HIGHEST)
    public void clickItems(PlayerInteractEvent e) {
        PaymentCanceledEvent event = new PaymentCanceledEvent(e.getPlayer(), CancelReason.RIGHT_CLICK);
        if (e.getAction() == Action.LEFT_CLICK_AIR || e.getAction() == Action.LEFT_CLICK_BLOCK) return;
        EquipmentSlot equipmentSlot = e.getHand();
        assert equipmentSlot != null;
        if (equipmentSlot.equals(EquipmentSlot.HAND))
        {
            NamespacedKey key = new NamespacedKey(plugin, "isQRCode");
            ItemStack clicked = e.getPlayer().getInventory().getItemInMainHand();
            ItemMeta itemMeta;
            if (clicked.getType() == Material.FILLED_MAP)
                itemMeta = clicked.getItemMeta();
            else return;
            if (itemMeta == null) return;
            if (haveQRFlag(key, clicked)) {
                e.getPlayer().getInventory().getItemInMainHand().setAmount(0);
                Bukkit.getPluginManager().callEvent(event);
            }
        }
    }

}
